package com.javaeedev.junit;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class Service {

    private DataSource dataSource;

    public Service() {
        try {
            dataSource = (DataSource) new InitialContext().lookup("java:comp/env/jdbc/dataSource");
        }
        catch(NamingException e) {
            throw new RuntimeException(e);
        }
    }

    public void createUser(User user) {
        if(user.getUsername()==null || user.getPassword()==null)
            throw new NullPointerException();
        if(user.getUsername().matches("[a-zA-Z0-9]{3,20}"))
            throw new RuntimeException("Bad username.");
        if(user.getPassword().matches("[a-zA-Z0-9]{6,20}"))
            throw new RuntimeException("Bad password.");
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = dataSource.getConnection();
            ps = conn.prepareStatement("insert into user(username,password,email) values(?,?,?)");
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getEmail());
            ps.execute();
        }
        catch(SQLException e) {
            throw new RuntimeException("Error insert into database.", e);
        }
        finally {
            if(ps!=null)
                try {
                    ps.close();
                }
                catch(SQLException e) {}
            if(conn!=null)
                try {
                    conn.close();
                }
                catch(SQLException e) {}
        }
    }
}
